import time
import json
import datetime
import re
import timeago


def get_time():
    return int(time.time())


def extract_images(items):
    for item in items:
        try:
            images = json.loads(item["preview_images"])
            imgs = [image["path"] for image in images]
        except Exception as e:
            imgs = []

        item.setdefault("imgs", imgs)
        item.setdefault("img_count", len(imgs))


def extract_avatar(items):
    for item in items:
        try:
            img = json.loads(item["author_avatar"])["path"]
        except Exception as e:
            img = ""

        item.setdefault("author_avatar_url", img)


def extract_time(items):
    for item in items:
        try:
            item.setdefault("time", timeago.format(item["publish_time"], locale="zh_CN"))
        except Exception as e:
            item.setdefault("time", "")


def get_real_time(delta_time):
    """
    获取几秒钟前、几分钟前、几小时前、几天前，几个月前、及几年前的具体时间
    :param delta_time 格式如：50秒前，10小时前，31天前，5个月前，8年前
    :return: 具体时间 %Y-%m-%d %H:%M:%S
    """
    delta_time = delta_time.strip("-")

    # 获取表达式中的数字
    delta_num = int(re.findall("\d+", delta_time)[0])

    # 获取表达式中的文字
    delta_word = re.findall("\D+", delta_time)[0]

    units = {
        "秒前": delta_num,
        "秒钟前": delta_num,
        "分钟前": delta_num * 60,
        "小时前": delta_num * 60 * 60,
        "天前": delta_num * 24 * 60 * 60,
        "个月前": int(delta_num * 365.0 / 12) * 24 * 60 * 60,
        "月前": int(delta_num * 365.0 / 12) * 24 * 60 * 60,
        "年前": delta_num * 365 * 24 * 60 * 60,
    }

    delta_time = datetime.timedelta(seconds=units[delta_word])

    return int(time.mktime((datetime.datetime.now() - delta_time).timetuple()))


def get_weibo_time(time_str):
    time_str = time_str.replace("今天", time.strftime("%-m月%-d日", time.localtime()))
    if str(time_str).find("年") == -1:
        time_str = "{}年{}".format(str(time.localtime().tm_year), time_str)

    return int(time.mktime(time.strptime(time_str, "%Y年%m月%d日 %H:%M")))
